using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

// TODO: replace this with the type you want to read.
using TRead = AfterlifeLib.Levels.Level;
using AfterlifeLib.Lighting;
using AfterlifeLib.Levels;

namespace AfterlifeLib.ContentTypeReaders
{
    /// <summary>
    /// This class will be instantiated by the XNA Framework Content
    /// Pipeline to read the specified data type from binary .xnb format.
    /// 
    /// Unlike the other Content Pipeline support classes, this should
    /// be a part of your main game project, and not the Content Pipeline
    /// Extension Library project.
    /// </summary>
    public class LevelTypeReader : ContentTypeReader<TRead>
    {
        //Level file structure
        // - GameTilesetPath
        // - The amount of TileLayers
        // - All the TileLayers
        // - The only CollisionLayer
        // - The AmbientColor
        // - The amount of Lights
        // - All the Lights
        protected override TRead Read(ContentReader input, TRead existingInstance)
        {
            string gameTilesetPath = input.ReadString();

            int tileLayerCount = input.ReadInt32();

            List<TileLayer> tileLayers = new List<TileLayer>();
            for (int i = 0; i < tileLayerCount; i++)
            {
                TileLayer layer = new TileLayer();
                layer.ReadBinary(input);
                tileLayers.Add(layer);
            }

            CollisionLayer collisionLayer = new CollisionLayer();
            collisionLayer.ReadBinary(input);

            Color ambientColor = input.ReadColor();

            int lightCount = input.ReadInt32();
            List<Light> lights = new List<Light>();
            for (int i = 0; i < lightCount; i++)
            {
                lights.Add(new Light(
                    input.ReadString(),
                    input.ReadColor(),
                    input.ReadSingle(),
                    input.ReadSingle(),
                    input.ReadVector3())
                );
            }

            Texture2D tileset = input.ContentManager.Load<Texture2D>(gameTilesetPath);

            TRead level = new TRead(tileset, null, gameTilesetPath, tileLayers, collisionLayer, ambientColor, lights);

            return level;
        }
    }
}
